import React, { useEffect, useState } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Table,
  Image,
  Switch,
  Space,
  Modal,
  message
} from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { NavLink } from 'react-router-dom'
import type { UserQuery, User, UpdateUserTpye, AddUserType } from '@/types/user'
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import type { ColumnsType } from 'antd/es/table'

export default function index () {
  const [userQuery, setUserQuery] = useState<UserQuery>({
    page: 1,
    pageSize: 2,
    nickname: ''
  })
  const [userList, setUserList] = useState([] as User[])
  const [total, setTotal] = useState(0)
  const [nickname, setNickname] = useState('')

  //获取数据
  const getUserListData = async () => {
    const res = await getUserList(userQuery)
    setUserList(res.data.items)
    setTotal(res.data.total)
  }
  useEffect(() => {
    getUserListData()
  }, [userQuery])
  //搜索
  const search = () => {
    setUserQuery({ ...userQuery, nickname })
  }

  const columns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'adminname',
      key: 'adminname'
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      render: avatar => {
        return <Image style={{ width: 50, height: 50 }} src={avatar} />
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: status => {
        return <Switch checked={status === 1} />
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, recod) => {
        return (
          <Space>
            <Button type='primary' onClick={() => update(recod)}>
              修改
            </Button>
            <Button type='primary' danger onClick={() => del(recod.adminid)}>
              删除
            </Button>
          </Space>
        )
      }
    }
  ]
  //新增&修改
  const [open, setOpen] = useState(false)
  const [mode, setMode] = useState<'add' | 'edit'>('add')
  //获取到form表单   可以用ref
  const [formInstance] = Form.useForm()
  const [userForm, setUserForm] = useState<UpdateUserTpye>({
    adminname: '',
    adminid: '',
    nickname: '',
    status: 1
  })

  const submit = async () => {
    try {
      await formInstance.validateFields()
      if (mode === 'add') {
        delete userForm.adminid
        await addUser(userForm)
      } else {
        await updateUser(userForm)
      }
      message.success(mode === 'add' ? '新增成功' : '修改成功')
      // 关闭弹框
      setOpen(false)
      getUserListData()
    } catch (error) {
      console.log(error)
    }
  }
  //修改
  const update = (value: User) => {
    //给模型赋值
    setUserForm(value)
    //设置open为true
    setOpen(true)
    setMode('edit')
    //调用form的setFieldsValue方法给表单的每个字段赋值   对原始的input进行了封装
    formInstance.setFieldsValue(value)
  }
  // 清空表单内容
  useEffect(() => {
    if (!open) {
      setMode('add')
      //清空模型
      formInstance.resetFields()
      setUserForm({} as UpdateUserTpye)
    }
  }, [open])
  //删除用户
  const del = (adminid: string) => {
    Modal.confirm({
      title: '温馨提示',
      content: '确认删除吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await deleteUser(adminid)
        setUserQuery({ ...userQuery, page: 1 })

        getUserListData()
      }
    })
  }
  return (
    <div>
      <Card>
        <Breadcrumb
          items={[
            {
              title: <NavLink to='/'>首页</NavLink>
            },
            {
              title: '用户管理'
            },
            {
              title: '用户列表'
            }
          ]}
        />
        <Form layout='inline' style={{ marginTop: 20 }} size='large'>
          <Form.Item label='昵称'>
            <Input
              placeholder='请输入昵称进行搜索'
              style={{ width: 300 }}
              value={nickname}
              onChange={(e: any) => {
                setNickname(e.target.value)
              }}
            />
          </Form.Item>
          <Form.Item>
            <Button type='primary' onClick={search}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type='default'
              onClick={() => {
                setOpen(true)
              }}
            >
              新增用户
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          size='large'
          columns={columns}
          rowKey='adminid'
          dataSource={userList}
          pagination={{
            position: ['bottomCenter'],
            current: userQuery.page,
            pageSize: userQuery.pageSize,
            pageSizeOptions: [1, 2, 5, 10],
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共${total}条`,
            onChange: (page, pageSize) => {
              setUserQuery({ ...userQuery, page, pageSize })
            }
          }}
        />
      </Card>
      <Modal
        title={mode == 'add' ? '新增用户' : '修改用户'}
        open={open}
        onOk={submit}
        onCancel={() => {
          setOpen(false)
        }}
        okText='确认'
        cancelText='取消'
        style={{ width: 600 }}
        forceRender
        destroyOnClose={true}
      >
        <Form
          size='large'
          form={formInstance}
          name='basic'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete='off'
          labelAlign='left'
        >
          <Form.Item
            label='用户名称'
            name='adminname'
            rules={[{ required: true, message: '用户名不能为空!' }]}
          >
            <Input
              value={userForm.adminname}
              onChange={e =>
                setUserForm({ ...userForm, adminname: e.target.value })
              }
              disabled={mode === 'edit'}
            />
          </Form.Item>

          <Form.Item
            label='用户昵称'
            name='nickname'
            rules={[{ required: true, message: '用户昵称不能为' }]}
          >
            <Input
              value={userForm.nickname}
              onChange={e =>
                setUserForm({ ...userForm, nickname: e.target.value })
              }
            />
          </Form.Item>
          <Form.Item label='状态' name='status' labelAlign='right'>
            <Switch
              checked={userForm.status === 1}
              onChange={checked =>
                setUserForm({ ...userForm, status: checked ? 1 : 0 })
              }
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
